package com.hzsparrow.ai.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzsparrow.ai.entity.KnowledgeBase;
import com.hzsparrow.ai.mapper.KnowledgeBaseMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 知识库服务实现类
 */
@Service
public class KnowledgeBaseServiceImpl extends ServiceImpl<KnowledgeBaseMapper, KnowledgeBase> implements KnowledgeBaseService {

    @Override
    public KnowledgeBase createKnowledgeBase(KnowledgeBase knowledgeBase) {
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        knowledgeBase.setCreateTime(now);
        knowledgeBase.setUpdateTime(now);
        
        // 保存知识库
        this.save(knowledgeBase);
        return knowledgeBase;
    }

    @Override
    public KnowledgeBase getKnowledgeBase(Long id) {
        return this.getById(id);
    }

    @Override
    public KnowledgeBase updateKnowledgeBase(KnowledgeBase knowledgeBase) {
        // 设置更新时间
        knowledgeBase.setUpdateTime(LocalDateTime.now());
        
        // 更新知识库
        this.updateById(knowledgeBase);
        return knowledgeBase;
    }

    @Override
    public boolean deleteKnowledgeBase(Long id) {
        return this.removeById(id);
    }

    @Override
    public List<KnowledgeBase> getUserKnowledgeBases(Long userId) {
        LambdaQueryWrapper<KnowledgeBase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(KnowledgeBase::getCreateUserId, userId)
                    .orderByDesc(KnowledgeBase::getCreateTime);
        return this.list(queryWrapper);
    }

    @Override
    public Page<KnowledgeBase> listKnowledgeBases(int page, int size, Long userId) {
        Page<KnowledgeBase> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<KnowledgeBase> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果指定了用户ID，则查询该用户的知识库
        if (userId != null) {
            queryWrapper.eq(KnowledgeBase::getCreateUserId, userId);
        }
        
        queryWrapper.orderByDesc(KnowledgeBase::getCreateTime);
        return this.page(pageParam, queryWrapper);
    }
} 